$(() => {
  let laypage = layui.laypage;
  let flat = true;
  let data = {
    pagenum: 1,
    pagesize: 2,
  };
  getCategory();
  getAtc(data);
  function getAtc(data) {
    $.ajax({
      url: '/my/article/list',
      data: data,
      success(res) {
        if (res.status === 0) {
          let str = template('listAtc', res);
          $('tbody').html(str);
          renderAtr(res.total);
        }
      },
    });
  }
  function renderAtr(num) {
    laypage.render({
      layout: ['limit', 'prev', 'page', 'next', 'count', 'skip'],
      limits: [2, 4, 6, 8, 10],
      curr: data.pagenum,
      elem: 'page',
      limit: data.pagesize,
      count: num,
      jump(obj, first) {
        if (!first) {
          data.pagenum = obj.curr;
          data.pagesize = obj.limit;
          getAtc(data);
        }
      },
    });
  }
  $('tbody').on('click', '.delete', function () {
    let id = $(this).parents('tr').attr('data-id');
    layer.confirm(
      '您确定要删除此篇文章吗?',
      { icon: 3, title: '删除文章' },
      function (index) {
        layer.close(index);
        $.ajax({
          url: '/my/article/delete/' + id,
          success(res) {
            if (res.status === 0) {
              layer.msg(res.message);
              if (($('.delete').length = 1)) {
                data.pagenum = data.pagenum - 1;
                data.pagenum = Math.max(data.pagenum, 1);
              }
              getAtc(data);
            } else {
              layer.msg(res.message);
            }
          },
        });
      }
    );
  });
  $('#filterForm').submit(function (e) {
    e.preventDefault();
    let fd = new FormData(this);
    fd.forEach(function (v, i) {
      data[i] = v;
    });
    getAtc(data);
  });
  $('tbody').on('click', '.editBtn', function () {
    let id = $(this).parents('tr').attr('data-id');
    location.href = '/bigevent/article/edit.html?id=' + id;
  });
});
